package com.rul.mars.order.service.impl;

import com.rul.mars.mbg.mapper.ProductMapper;
import com.rul.mars.mbg.model.Product;
import com.rul.mars.order.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 库存服务实现
 * @author RuL
 */
@Service
public class StockServiceImpl implements StockService {

    @Autowired
    private ProductMapper productMapper;

    /**
     * 锁定商品库存，开启事务保证库存正确
     *
     * @param productId  商品ID
     * @param productNum 商品数量
     */
    @Transactional
    @Override
    public void lockStock(Long productId, Integer productNum) {
        Product product = productMapper.selectByPrimaryKey(productId);
        product.setStock(product.getStock() - productNum);
        productMapper.updateByPrimaryKeySelective(product);
    }

    /**
     * 解锁商品库存，开启事务保证库存正确
     *
     * @param productId  商品ID
     * @param productNum 商品数量
     */
    @Transactional
    @Override
    public void unlockStock(Long productId, Integer productNum) {
        Product product = productMapper.selectByPrimaryKey(productId);
        product.setStock(product.getStock() + productNum);
        productMapper.updateByPrimaryKeySelective(product);
    }
}
